import os
from pathlib import Path
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import font_manager as fm
import seaborn as sns
import pandas as pd

# ------------------------------
# Data (from report, 30D window)
# ------------------------------
rows = [
    {"name": "OhYeah888999", "return_pct": 76.47, "pnl": 17944.03, "follower_pnl": 0.00, "sharpe": 2.92, "max_dd": 31.24, "win_rate": 96.00},
    {"name": "48ClubIan", "return_pct": 14.26, "pnl": 42611.17, "follower_pnl": -49641.51, "sharpe": 1.22, "max_dd": 9.70, "win_rate": 44.87},
    {"name": "Crypto Lama", "return_pct": 10.25, "pnl": 46572.07, "follower_pnl": 309417.59, "sharpe": 1.35, "max_dd": 15.47, "win_rate": 98.93},
    {"name": "JaBBBi", "return_pct": 7.41, "pnl": 31738.80, "follower_pnl": 6516.73, "sharpe": 1.45, "max_dd": 17.61, "win_rate": 44.90},
    {"name": "钱翻一番_Money2X", "return_pct": 6.12, "pnl": 16771.06, "follower_pnl": 5245.81, "sharpe": 2.38, "max_dd": 2.79, "win_rate": 96.99},
]

df = pd.DataFrame(rows)

# Ensure output directory
out_dir = Path(__file__).resolve().parents[1] / "final" / "figs"
out_dir.mkdir(parents=True, exist_ok=True)

# Aesthetics & Fonts (macOS PingFang)
# Prefer PingFang SC on macOS to properly render Chinese labels.
rcParams["font.family"] = ["sans-serif"]
rcParams["font.sans-serif"] = [
    "PingFang SC",           # macOS system Chinese font
    "PingFang HK",
    "Heiti TC",
    "Hiragino Sans GB",
    "Apple Symbols",
    "Arial Unicode MS",
    "DejaVu Sans",
]
rcParams["axes.unicode_minus"] = False  # ensure minus sign renders correctly

sns.set(style="whitegrid", context="talk")
HIGHLIGHT = "钱翻一番_Money2X"
colors = ["#4C78A8" if n != HIGHLIGHT else "#E45756" for n in df["name"]]

# Try to explicitly load PingFang from typical macOS locations
PINGFANG_CANDIDATES = [
    "/System/Library/Fonts/PingFang.ttc",
    "/System/Library/Fonts/PingFangSC.ttc",
    "/System/Library/Fonts/Supplemental/PingFang.ttc",
]
fp = None
for p in PINGFANG_CANDIDATES:
    if Path(p).exists():
        try:
            fp = fm.FontProperties(fname=p)
            break
        except Exception:
            pass

def apply_font(ax):
    if fp is None:
        return
    ax.set_title(ax.get_title(), fontproperties=fp)
    ax.set_xlabel(ax.get_xlabel(), fontproperties=fp)
    ax.set_ylabel(ax.get_ylabel(), fontproperties=fp)
    for lbl in ax.get_xticklabels() + ax.get_yticklabels():
        lbl.set_fontproperties(fp)

# 1) Return vs MaxDD (two subplots)
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Return
sns.barplot(x="return_pct", y="name", data=df, ax=axes[0], palette=colors, orient="h")
axes[0].set_title("近30天收益率(%)")
axes[0].set_xlabel("收益率 %")
axes[0].set_ylabel("")
apply_font(axes[0])
# MaxDD
sns.barplot(x="max_dd", y="name", data=df, ax=axes[1], palette=colors, orient="h")
axes[1].set_title("近30天最大回撤(%)")
axes[1].set_xlabel("最大回撤 %")
axes[1].set_ylabel("")
apply_font(axes[1])
plt.tight_layout()
fig_path1 = out_dir / "top5_return_maxdd.png"
plt.savefig(fig_path1, dpi=180)
plt.close()

# 2) Sharpe comparison (16:9)
plt.figure(figsize=(12.8, 7.2))  # 16:9 aspect ratio
ax2 = sns.barplot(x="sharpe", y="name", data=df, palette=colors, orient="h")
plt.title("近30天夏普比对比", fontproperties=fp if fp else None)
plt.xlabel("夏普比", fontproperties=fp if fp else None)
plt.ylabel("", fontproperties=fp if fp else None)
apply_font(ax2)
plt.tight_layout()
fig_path2 = out_dir / "top5_sharpe.png"
plt.savefig(fig_path2, dpi=180)
plt.close()

print(f"Saved: {fig_path1}")
print(f"Saved: {fig_path2}")
